<?php
include '../connectdb.php';

function get_parrent_path($path) {
    /* if the path has a trailing slash */
    if ($path[strlen($path) - 1] === '/')
        $path = substr($path, 0, strlen($path) - 1); /* remove it */
    /* if the position of the rightmost '/' is not the first character in the path */
    if ($pos = strrpos($path, '/'))
        $path = substr($path, 0, $pos); /* remove the '/' and everthing after */
    /* if the rightmost '/' was the first character */
    if ($pos === 0)
        $path = '/'; /* set the path to root */
    return $path; // return the path to the parrent directory 
}

if (isset($_GET['del'])) {
    $q = "delete from home_stay where home_stay_id=" . $_GET["home_stay_id"];
    mysqli_query($link, $q);
    header('Location: main.php?homestay=true');
    die;
}
if (isset($_POST['action'])) {
    $p = (isset($_POST['preview'])) ? 1 : 0;
    $q = "home_stay set home_stay_name='" . $_POST["name"] . "', home_stay_location='" . $_POST["location"] . "'";
    $q.= ", home_stay_detail='" . $_POST["detail"] . "', is_preview=" . $p . "";

    if ($_POST['action'] == 'add') {
        $q = "insert into " . $q;
    } else { // edit
        $q = "update " . $q . " where home_stay_id=" . $_POST["home_stay_id"];
        $id = $_POST["home_stay_id"];
    }
    mysqli_query($link, $q);

    if ($_POST['action'] == 'add') {
        $id = mysqli_insert_id();
        //printf("Last inserted record has id %d\n", $id);
    }

    // Simple PHP Upload Script:  http://coursesweb.net/php-mysql/
    $path = 'photos/';
    $uploadpath = get_parrent_path(__DIR__) . '/' . $path;      // directory to store the uploaded files
    $max_size = 2000;          // maximum file size, in KiloBytes
    $alwidth = 2000;            // maximum allowed width, in pixels
    $alheight = 2000;           // maximum allowed height, in pixels
    $allowtype = array('bmp', 'gif', 'jpg', 'jpeg', 'png');        // allowed extensions

    if (isset($_FILES['picture']) && strlen($_FILES['picture']['name']) > 1) {
        $sepext = explode('.', strtolower($_FILES['picture']['name']));
        $type = end($sepext);       // gets extension
        $fileName = $id . '_' . strtotime(date('Y-m-d H:i:s'));
        $uploadpath = $uploadpath . $fileName . '.' . $type;       // gets the file name
        list($width, $height) = getimagesize($_FILES['picture']['tmp_name']);     // gets image width and height
        $err = '';         // to store the errors
        // Checks if the file has allowed type, size, width and height (for images)
        if (!in_array($type, $allowtype))
            $err .= 'The file: <b>' . $_FILES['picture']['name'] . '</b> not has the allowed extension type.';
        if ($_FILES['picture']['size'] > $max_size * 1000)
            $err .= '<br/>Maximum file size must be: ' . $max_size . ' KB.';
        if (isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight))
            $err .= '<br/>The maximum Width x Height must be: ' . $alwidth . ' x ' . $alheight;

        // If no errors, upload the image, else, output the errors
        if ($err == '') {
            if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadpath)) {
                /* echo 'File: <b>' . basename($_FILES['picture']['name']) . '</b> successfully uploaded:';
                  echo '<br/>File type: <b>' . $_FILES['picture']['type'] . '</b>';
                  echo '<br />Size: <b>' . number_format($_FILES['picture']['size'] / 1024, 3, '.', '') . '</b> KB'; */
                /* if (isset($width) && isset($height))
                  echo '<br/>Image Width x Height: ' . $width . ' x ' . $height; */
                //echo '<br/><br/>Image address: <b>http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['REQUEST_URI']), '\\/') . '/' . $uploadpath . '</b>';

                if ($id > 0) {
                    $sql = "SELECT home_stay_picture FROM home_stay WHERE home_stay_id = '$id'";
                    $result = mysqli_query($link, $sql);
                    $row = mysqli_fetch_array($result);
                    if (sizeof($row) > 0) {
                        @unlink(get_parrent_path(__DIR__) . '/' . $row['home_stay_picture']);
                        $q = "update home_stay SET home_stay_picture = '$path$fileName." . $type . "' WHERE home_stay_id = " . $id;
                    }
                    mysqli_query($link, $q);
                }
            }
            else
                echo '<b>Unable to upload the file.</b>';
        }
        else
            echo $err;
    }
    /* print_r($_FILES);
      exit; */
    for ($i = 0; $i < count($_FILES["sub_picture"]["name"]); $i++) {
        if (trim($_FILES["sub_picture"]["tmp_name"][$i]) != "") {
            $hid_sub_picture = isset($_POST['hid_sub_picture'][$i]) ? $_POST['hid_sub_picture'][$i] : 0;

            $uploadpath8 = get_parrent_path(__DIR__) . '/' . $path . 'sub/';      // directory to store the uploaded files
            $sepext = explode('.', strtolower($_FILES['sub_picture']['name'][$i]));
            $type = end($sepext);
            $fileName = $id . '_sub_' . strtotime(date('Y-m-d H:i:s')) . $i;
            $uploadpath8 = $uploadpath8 . $fileName . '.' . $type;
            list($width, $height) = getimagesize($_FILES['sub_picture']['tmp_name'][$i]);
            $err = '';
            if (!in_array($type, $allowtype))
                $err .= 'The file: <b>' . $_FILES['sub_picture']['name'][$i] . '</b> not has the allowed extension type.';
            if ($_FILES['sub_picture']['size'][$i] > $max_size * 1000)
                $err .= '<br/>Maximum file size must be: ' . $max_size . ' KB.';
            if (isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight))
                $err .= '<br/>The maximum Width x Height must be: ' . $alwidth . ' x ' . $alheight;

            if ($err == '') {
                if (move_uploaded_file($_FILES['sub_picture']['tmp_name'][$i], $uploadpath8)) {
                    if ($id > 0) {
                        $sql8 = "SELECT picture_address FROM picture WHERE picture_id = '$hid_sub_picture'";
                        $result8 = mysqli_query($link, $sql8);
                        $row8 = mysqli_fetch_array($result8);
                        if (sizeof($row8) > 0) {
                            @unlink(get_parrent_path(__DIR__) . '/' . $row8['picture_address']);
                            $q8 = "update picture SET picture_address = '" . $path . "sub/" . $fileName . '.' . $type . "' WHERE picture_id = " . $hid_sub_picture;
                        } else {
                            $q8 = "insert into picture (picture_address, home_stay_id) VALUES('" . $path . "sub/" . $fileName . '.' . $type . "', '$id')";
                        }
                        mysqli_query($link, $q8);
                    }
                }
                else
                    echo '<b>Unable to upload the file.</b>';
            }
            else
                echo $err;
        }
    }
}
if (isset($_GET["add"]) || isset($_GET["edit"])) {
    if (isset($_GET["edit"])) {
        $q = "select * from home_stay where home_stay_id = " . $_GET["home_stay_id"];
        $result = mysqli_query($link, $q);
        $row = mysqli_fetch_array($result);
        $url = "main.php?homestay=true"; //&edit=true&customer_id=" . $_GET["customer_id"];
        $action = 'edit';
        $checked = ($row["is_preview"] == 1) ? 'checked' : '';

        $q2 = "select * from picture where home_stay_id=" . $_GET["home_stay_id"];
        $result2 = mysqli_query($link, $q2);
    } else {
        $url = "main.php?homestay=true"; //&add=true";
        $action = 'add';
        $checked = '';
    }
    ?>
    <form action="<?php echo $url ?>" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="<?php echo $action ?>" />
        <input type="hidden" name="home_stay_id" value="<?php echo $_GET["home_stay_id"] ?>" />
        <table border="1" width="764">
            <tr>
                <td colspan="2" align="center"><h3>Add/Edit Home_Stay</h3></td>
            </tr>
            <tr>
                <td>name</td>
                <td><input type="text" name="name" value="<?php echo $row['home_stay_name'] ?>" /></td>
            </tr>
            <tr>
                <td>location</td>
                <td><input type="text" name="location" value="<?php echo $row['home_stay_location'] ?>" /></td>
            </tr>
            <tr>
                <td>detail</td>
                <td><textarea name="detail"><?php echo $row['home_stay_detail'] ?></textarea></td>
            </tr>
            <tr>
                <td>picture</td>
                <td>
                    <?php
                    if ($row['home_stay_picture'] != '') {
                        ?>
                        <img src="../<?php echo $row['home_stay_picture']; ?>" width="150px" height="150px" />
                        <?php
                    }
                    ?>
                    <br />
                    <input type="file" name="picture">
                </td>
            </tr>
            <tr>
                <td>sub picture</td>
                <td>
                    <?php
                    if ($result2) {
                        $n = mysqli_num_rows($result2);
                        while ($row2 = mysqli_fetch_array($result2)) {
                            ?>
                            <img src="../<?php echo $row2['picture_address']; ?>" width="150px" height="150px" />
                            <input type="file" name="sub_picture[]">
                            <input type="hidden" name="hid_sub_picture[]" value="<?php echo $row2['picture_id']; ?>"/>
                            <?php
                        }
                        for ($i = $n; $i < 5; $i++) {
                            ?>
                            <br />
                            <img src="../images/no_image/no_image.jpeg" width="150px" height="150px" />
                            <input type="hidden" name="hid_sub_picture[]" value=""/>
                            <input type="file" name="sub_picture[]">
                            <?php
                        }
                    } else {
                        ?>
                        <br />
                        <input type="hidden" name="hid_sub_picture[]" value=""/>
                        <input type="file" name="sub_picture[]">
                    <?php } ?>
                </td>
            </tr>
            <tr>
                <td>preview</td>
                <td><input type="checkbox" name="preview" value="1" <?php echo $checked; ?> ></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="submit" /> <input type="reset" value="reset"></td>
            </tr>
        </table>
    </form>
    <?php
} else {
    ?>
    <script type="text/javascript">
        function confirm_delete(url) {
            if (confirm("โปรดยืนยันการลบข้อมูล")) {
                location.href = url;
            }
        }
    </script>
    <table border="1" width="764">
        <tr>
            <td colspan="7" align="center"><h3>Home_Stay Management</h3></td>
        </tr>
        <tr>
            <td colspan="7" align="right"><a href="main.php?homestay=true&add=true">+Add</a></td>
        </tr>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>location</td>
            <td>detail</td>
            <td>preview</td>
            <td>edit</td>
            <td>delete</td>
        </tr>
        <?php 
        $q = "SELECT * FROM home_stay WHERE home_stay_id IN(".implode(',', $_SESSION['permission']).")";
        $result = mysqli_query($link, $q);
        while ($row = mysqli_fetch_array($result)) {
            ?>
            <tr>
                <td><a href="main.php?homestay_room=true&home_stay_id=<?php echo $row['home_stay_id']; ?>"><?php echo $row['home_stay_id']; ?></a></td>
                <td><?php echo $row['home_stay_name']; ?></td>
                <td><?php echo $row['home_stay_location']; ?></td>
                <td><?php echo nl2br($row['home_stay_detail']); ?></td>
                <td><?php echo $row['is_preview']; ?></td>
                <td><a href="main.php?homestay=true&edit=true&home_stay_id=<?php echo $row['home_stay_id']; ?>">edit</a></td>
                <td><a href="javascript:confirm_delete('main.php?homestay=true&del=true&home_stay_id=<?php echo $row['home_stay_id'];
            ?>');">delete</a></td>
            </tr>
            <?php
        }
        ?>
    </table>
    <?php
}
?>